# -*- coding: utf-8 -*-
from datetime import datetime, timedelta

from odoo import models, fields, api, _
from odoo.exceptions import ValidationError, UserError


class HROvertimeSheet(models.Model):
    _name = 'hr.overtime.sheet'
    _order = 'apply_date desc'
    _approve_by_level = True

    _inherit = ['portal.mixin', 'mail.thread', 'mail.activity.mixin', 'utm.mixin', 'base.approve']
    department_id = fields.Many2one('hr.department', string=u'部门', related='employee_id.department_id', store=True)
    apply_date = fields.Date(string=u'日期')
    name = fields.Char()
    type_id = fields.Many2one('hr.overtime.type', string=u'加班类别')
    line_ids = fields.One2many('hr.overtime', 'sheet_id')
    user_id = fields.Many2one('res.users', default=lambda self: self.env.uid)
    approve_flow_ids = fields.One2many('approve.flow', 'res_id', domain=[('res_model', '=', 'hr.overtime.sheet')])

    approval_record_ids = fields.One2many('approval.records', 'res_id',
                                          domain=[('res_model', '=', 'hr.overtime.sheet')])

    active = fields.Boolean(default=True)
    real_sheet_ids = fields.One2many('hr.overtime.sheet.real', 'sheet_id')
    has_real=fields.Boolean(compute='has_real_sheet')
    def has_real_sheet(self):
        for r in self:
            if r.real_sheet_ids:
                r.has_real=True
            else:
                r.has_real=False


    def action_archive(self):
        if not self.user_has_groups('hr_overtime.group_hr_over_time_manager'):
            raise UserError('只有加班管理员才有权限归档')
        super(HROvertimeSheet, self).action_archive()
    # real_state = fields.Selection([
    #     ('before','预报')
    #     ('draft', u'草稿'),
    #     ('cancel', u'取消'),
    #     ('to approve', u'待审核'),
    #     ('to confirm', u'待实报'),
    #     ('rejected', u'拒绝'),
    #     ('done', u'完成')
    # ], default='before', string=u'实报状态', compute='compute_real_state', store=True)
    # @api.depends('real_sheet_ids.state')
    # def compute_real_state(self):
    #     for record in self:
    #         if record.real_sheet_ids:
    #             record.real_state=record.real_sheet_ids[0].state
    #         else:
    #             record.real_state='before'

    def action_set_to_draft(self):
        self.state = 'draft'

    # def check_values(self):
    #     self.order_line.validate_the_price_unit()
    #     super(HROvertimeSheet, self).check_values()
    #     if not self.line_ids:
    #         raise UserError(u'请添加加班明细')

    def _default_employee(self):
        return self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)

    employee_id = fields.Many2one('hr.employee', default=_default_employee)

    def action_recompute(self):
        for r in self:
            r.line_ids.compute_resource_calendar_id()
            r.line_ids.compute_period()

    def check_values(self):
        for line in self.line_ids:
            if not line.resource_calendar_id:
                raise UserError('%s 找不到对应的班别')
        return super(HROvertimeSheet, self).check_values()

    # @api.onchange('department_id')
    # def onchange_department_id(self):
    #     line_ids = []
    #     if not self.apply_date:
    #         return
    #
    #     for e in self.department_id.member_ids:
    #         line_ids.append(
    #             (0, 0, {
    #                 'apply_date': self.apply_date,
    #                 'employee_id': e.id,
    #             }))
    #     self.line_ids = line_ids

    @api.model
    def create(self, vals):
        if not vals.get('name') or vals['name'] == _('New'):
            vals['name'] = self.env['ir.sequence'].next_by_code('hr.overtime.sheet') or _('New')
        return super(HROvertimeSheet, self).create(vals)

    def action_create_real_sheet(self):
        if not self.real_sheet_ids:
            self.env['hr.overtime.sheet.real'].create({
                'sheet_id': self.id,
            })

    def action_approve_done(self):
        super(HROvertimeSheet, self).action_approve_done()
        self.env['hr.overtime.sheet.real'].create({
            'sheet_id': self.id,
        })


